package com.lifeonwalden.ms.web.service.impl;

import com.lifeonwalden.ms.cache.service.CacheRuntimeService;
import com.lifeonwalden.ms.cache.service.CacheService;
import com.lifeonwalden.ms.common.logger.LoggerUtil;
import com.lifeonwalden.ms.web.bean.Person;
import com.lifeonwalden.ms.web.constant.CacheIdSet;
import com.lifeonwalden.ms.web.service.PersonService;
import org.apache.commons.lang3.RandomUtils;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class PersonServiceImpl implements PersonService {
    private final static Logger logger = LoggerUtil.getLogger(PersonServiceImpl.class);

    @Autowired
    private CacheRuntimeService cacheRuntimeService;

    @Override
    @Cacheable(cacheManager = "cacheManager", cacheNames = CacheIdSet.PERSON, key = "#name")
    public Person fetch(String name) {
        LoggerUtil.info(logger, "fetch", name);

        return new Person().setName(name).setAge((int)System.currentTimeMillis());
    }

    @Override
    @Cacheable(cacheManager = "secondsCacheManager", cacheNames = CacheIdSet.PERSON_15S, key = "#name")
    public Person fetch15s(String name) {
        LoggerUtil.info(logger, "fetch15s", name);

        return new Person().setName(name).setAge((int)System.currentTimeMillis());
    }

    @Override
    public Person fetch15s_other(String name) {

        Person person = cacheRuntimeService.get(CacheIdSet.PERSON_15S, name);
        if (null == person) {
            LoggerUtil.info(logger, "fetch15s_other", name);

            CacheService cacheService = cacheRuntimeService.makeOrFetchCacheWithId(CacheIdSet.PERSON_15S, TimeUnit.SECONDS, 15);
            person = new Person().setName(name).setAge((int)System.currentTimeMillis());
            cacheService.put(name, person);
        }

        return person;
    }

    @Override
    public Person fetch60s(String name) {
        Person person = cacheRuntimeService.get(CacheIdSet.PERSON_60S, name);
        if (null == person) {
            LoggerUtil.info(logger, "fetch60s", name);

            CacheService cacheService = cacheRuntimeService.makeOrFetchCacheWithId(CacheIdSet.PERSON_60S, TimeUnit.SECONDS, 60);
            person = new Person().setName(name).setAge((int)System.currentTimeMillis());
            cacheService.put(name, person);
        }

        return person;
    }
}
